import { View } from "@tarojs/components";
import Taro, { useDidShow, eventCenter, useDidHide } from "@tarojs/taro";
import React, { useState, useEffect, useRef } from "react";
import { IconFont } from "@nutui/icons-react-taro";
import { NoticeBar, Tour } from "@nutui/nutui-react-taro"; // 导入 Tour
import AuthUtil from "../../utils/api/auth";
import LoginPopupProvider from "../../components/LoginPopup/index";
import "./index.less";

function Home() {
  const token = Taro.getStorageSync("token");
  const [orders, setOrders] = useState([]); // 初始化订单列表
  const [loading, setLoading] = useState(false); // 加载状态
  const [showTour, setShowTour] = useState(token ? false : true); // 操作指引显示状态
  const targetPersonRef = useRef(null);
  const targetCompanyRef = useRef(null);

  const [maskSize, setMaskSize] = useState({ width: 60, height: 50 }); // 默认值

  const handleQuery = (value) => {
    const token = Taro.getStorageSync("token");
    if (!token) {
      showLoginToast();
    } else {
      Taro.navigateTo({
        url: `/pages/agreement/index?type=${value}`,
      });
    }
  };

  const showLoginToast = () => {
    eventCenter.trigger("showLogin", true);
    Taro.showToast({
      title: "请先登录账号",
      icon: "none",
    });
  };

  useDidShow(() => {
    console.log("useDidShow  home");

    const token = Taro.getStorageSync("token");
    if (!token) {
      setOrders([]);
    }
    if (!orders) return token && getOrderList(1);
  });

  useDidHide(() => {
    eventCenter.trigger("showLogin", false);
  });
  useEffect(() => {
    const token = Taro.getStorageSync("token");
    token && getOrderList(1);
  }, []); // 依赖于页码

  const handleViewAll = () => {
    const token = Taro.getStorageSync("token");
    if (!token) return;
    Taro.navigateTo({
      url: `/pages/buyList/index`,
    });
  };

  const formatDateTime = (dateTimeStr) => {
    const date = new Date(dateTimeStr);
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, "0");
    const day = date.getDate().toString().padStart(2, "0");
    const hours = date.getHours().toString().padStart(2, "0");
    const minutes = date.getMinutes().toString().padStart(2, "0");
    return `${year}-${month}-${day} ${hours}:${minutes}`;
  };

  const getOrderList = async (page) => {
    setLoading(true); // 开始加载
    try {
      const response = await AuthUtil.getOrder(page); // 调用你的 API 方法
      if (response && response.data) {
        const formattedOrders = response.data.map((order) => ({
          ...order,
          status: order.orderStatus.label,
          publishedDate: formatDateTime(order.publishedAt),
        }));
        setOrders(formattedOrders);
      }
    } catch (error) {
      console.error("获取订单列表失败:", error);
      Taro.showToast({
        title: "获取订单失败，请稍后重试",
        icon: "none",
      });
    } finally {
      setLoading(false); // 结束加载
    }
  };

  const goPage = (value) => {
    const url =
      value?.payStatus && value?.orderStatus.id === 2
        ? "/pages/detail/index"
        : "/pages/editContent/index";
    Taro.navigateTo({ url: `${url}?value=${JSON.stringify(value)}` });
  };

  const content = loading ? (
    <View className="loading">加载中...</View> // 显示加载状态
  ) : orders.length > 0 ? (
    orders.slice(0, 3).map(
      (
        order,
        index // 只取前三条数据
      ) => (
        <View key={index} className="order-item" onClick={handleViewAll}>
          <View className="order">
            订单类型：{order?.sellerType === "company" ? "公司" : "个人"}
          </View>
          <View className="order">申请时间：{order?.publishedDate}</View>
          <View className="order">车主姓名：{order?.realName}</View>
          <View className="order">订单状态：{order?.status}</View>
        </View>
      )
    )
  ) : (
    <View className="no-data">暂无数据</View>
  );

  const steps = [
    {
      content: "点击这里查看个人转让二手车",
      target: "target-person", // 使用 id 选择器
    },
    {
      content: "点击这里查看企业转让二手车",
      target: "target-company", // 使用 id 选择器
    },
    {
      content: "查看交易列表，快速了解订单状态",
      target: "order-list-title", // 交易列表标题的 id
    },
    {
      content: "右下角点击我的,即可登录", // 最后一步的提示内容
      target: "login-prompt", // 目标元素的 id
      location: "bottom-end", // 指引位置
    },
  ];

  useEffect(() => {
    // 在组件加载时，获取目标元素的尺寸
    if (targetPersonRef.current) {
      const { width, height } = targetPersonRef.current.getBoundingClientRect();
      setMaskSize({ width, height }); // 设置 Tour 的 mask 尺寸
    }
  }, [showTour]);

  return (
    <View className="home">
      <NoticeBar content={"网签小程序平台"} />
      <View className="main-content flex flex-column g-6">
        <div
          className="car_tow"
          id="target-person"
          ref={targetPersonRef}
          onClick={() => handleQuery("person")}
        >
          <h3>个人转让二手车</h3>
          <div className="describe">
            <div>
              持有中华人民共和国居民身份证或港澳台居住证的人员进行在线认证
            </div>
          </div>
        </div>
        <div
          className="car_tow"
          id="target-company"
          ref={targetCompanyRef}
          onClick={() => handleQuery("company")}
          style={{ background: "#009afa" }}
        >
          <h3>企业转让二手车</h3>
          <div className="describe">
            <div>企业出售名下二手车必须由受托人提供授权委托书</div>
          </div>
        </div>
        <View className="flex flex-column align-center g-6 mt-4 list orderList">
          <View className="home-list" id="order-list-title">
            <View className="left_list">交易列表</View>
            <View className="right_list" onClick={handleViewAll}>
              查看全部
            </View>
          </View>
          {content}
        </View>
      </View>

      <Tour
        className="nut-custom-tour"
        visible={showTour}
        onClose={() => setShowTour(false)}
        list={steps}
        location="bottom-start"
        offset={[0, 0]}
        maskWidth={maskSize.width} // 动态设置 maskWidth
        maskHeight={maskSize.height} // 动态设置 maskHeight
      />
      <LoginPopupProvider> </LoginPopupProvider>
    </View>
  );
}

export default Home;
